part of '../index.dart';

class MessageGift extends StatefulWidget {
  const MessageGift({super.key});

  @override
  State<MessageGift> createState() => _MessageGiftState();
}

class _MessageGiftState extends State<MessageGift>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late ChatProvider chatProvider;
  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: context.read<ChatProvider>().wrappers.length,
      vsync: this,
      initialIndex: 0,
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    chatProvider = context.read<ChatProvider>();
  }

  @override
  void dispose() {
    chatProvider.gift = null;
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final provider = context.read<ChatProvider>();
    return Stack(
      children: [
        Column(
          children: [
            TabBar(
              controller: _tabController,
              isScrollable: true,
              physics: const ClampingScrollPhysics(),
              dividerColor: Colors.transparent,
              tabAlignment: TabAlignment.start,
              indicatorSize: TabBarIndicatorSize.label,
              indicatorWeight: 1,
              indicatorPadding: const EdgeInsets.only(bottom: 6),
              indicator: const CustomTabBarIndicator(),
              // indicator: const ArcTabIndicator(
              //   color: Color(0xFF8673F6),
              //   height: 2,
              //   radius: 0,
              // ),
              unselectedLabelStyle:
                  const TextStyle(color: Color(0xFFA8A8A8), fontSize: 16),
              labelStyle: const TextStyle(
                color: Color(0xFF8A72FE),
                fontWeight: FontWeight.w700,
                fontSize: 16,
              ),
              tabs: provider.wrappers.map((e) => Tab(text: e.name)).toList(),
            ),
            Expanded(
              child: DecoratedBox(
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
                ),
                child: TabBarView(
                  controller: _tabController,
                  children: provider.wrappers
                      .map((e) =>
                          MessageGiftGrid(e, gifts: provider.getGifts(e)))
                      .toList(),
                ),
              ),
            ),
          ],
        ),
        Positioned(
          bottom: 12,
          left: 12,
          right: 12,
          child: SafeArea(
            top: false,
            child: Row(
              children: [
                _Recharge(onTap: () {
                  context.read<ChatProvider>().jumpRecharge();
                }),
                const Spacer(),
                const _Send(),
              ],
            ),
          ),
        )
      ],
    );
  }
}

class _Recharge extends StatelessWidget {
  const _Recharge({this.onTap});
  final VoidCallback? onTap;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
      decoration: BoxDecoration(
        color: const Color(0xFFF2F2F2),
        borderRadius: BorderRadius.circular(99),
      ),
      child: Row(
        children: [
          Image.asset(Images.icChatDiamond, width: 16, height: 16),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 3),
            child: ValueListenableBuilder(
              valueListenable: context.read<ChatProvider>().balance,
              builder: (context, value, child) {
                return Text(
                  '${value ?? 0}',
                  style: const TextStyle(
                    color: Color(0xFF1B1B1B),
                    fontWeight: FontWeight.w500,
                    fontSize: 18,
                  ),
                );
              },
            ),
          ),
          GestureDetector(
            onTap: onTap,
            behavior: HitTestBehavior.opaque,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(99),
                gradient: const LinearGradient(
                  colors: [Color(0xFF8A72FE), Color(0xFF6549EC)],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                ),
              ),
              child: Text(
                T.current.c_recharge,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

class _Send extends StatefulWidget {
  const _Send();

  @override
  State<_Send> createState() => __SendState();
}

class __SendState extends State<_Send> {
  final _numbers = [1, 7, 17, 77, 777];

  void _onSendGift() async {
    final provider = context.read<ChatProvider>();
    final price = provider.gift?.price;
    final count = provider.giftCount;
    final balance = provider.balance.value;
    if (balance == null || balance <= 0) {
      EasyLoading.showToast(T.current.c_no_balance);
      return;
    }
    if (price == null) return;
    d(String s) => Decimal.parse(s);
    final total =
        (d(price.toString()) * d(count.toString())).toDouble().toInt();
    if (balance < total) {
      EasyLoading.showToast(T.current.c_no_balance);
      return;
    }
    Decimal.parse('0.2') + Decimal.parse('0.1');
    provider.sendGiftMessage();
  }

  Widget _counter(int value) {
    final last = value == _numbers.last;
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pop();
        context.read<ChatProvider>().setGiftCount(value);
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        width: 50,
        padding: const EdgeInsets.symmetric(vertical: 10),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: const Color(0xFFF2F2F2),
          border: Border(
            bottom: BorderSide(color: last ? Colors.transparent : Colors.white),
          ),
        ),
        child: Text(
          '$value',
          style: TextStyle(
              fontWeight: FontWeight.w500,
              color: context.read<ChatProvider>().giftCount == value
                  ? const Color(0xFF333333)
                  : const Color(0xFFC1C1C1)),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final provider = context.watch<ChatProvider>();
    return Row(
      children: [
        CustomPopup(
          showArrow: false,
          contentPadding: EdgeInsets.zero,
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: _numbers.map(_counter).toList(),
          ).clipRRect(5),
          barrierColor: Colors.transparent,
          contentDecoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: const Color(0xFFF2F2F2),
          ),
          child: Container(
            padding: const EdgeInsets.fromLTRB(10, 4, 4, 4),
            constraints: const BoxConstraints(minWidth: 60),
            alignment: Alignment.center,
            decoration: const BoxDecoration(
              color: Color(0xFFF2F2F2),
              borderRadius: BorderRadiusDirectional.horizontal(start: Radius.circular(99)),
            ),
            child: Row(
              children: [
                Text(
                  '${provider.giftCount}',
                  style: const TextStyle(
                    color: Color(0xFF1B1B1B),
                    fontWeight: FontWeight.w500,
                    fontSize: 18,
                  ),
                ),
                const Icon(Icons.keyboard_arrow_up, size: 15),
              ],
            ),
          ),
        ),
        GestureDetector(
          onTap: () => _onSendGift(),
          behavior: HitTestBehavior.opaque,
          child: Container(
            padding: const EdgeInsets.fromLTRB(6, 4, 8, 4),
            decoration: const BoxDecoration(
              color: Colors.green,
              borderRadius: BorderRadiusDirectional.horizontal(end: Radius.circular(99)),
              gradient: LinearGradient(
                colors: [Color(0xFF8A72FE), Color(0xFF6549EC)],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
              ),
            ),
            child: Text(
              T.current.c_send,
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 17,
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class ArcTabIndicator extends Decoration {
  final Color color;
  final double height;
  final double radius;

  const ArcTabIndicator({
    required this.color,
    this.height = 3.0,
    this.radius = 8.0,
  });

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _ArcPainter(color: color, height: height, radius: radius);
  }
}

class _ArcPainter extends BoxPainter {
  final Color color;
  final double height;
  final double radius;

  _ArcPainter({
    required this.color,
    required this.height,
    required this.radius,
  });

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    assert(configuration.size != null);
    final Rect rect = offset & configuration.size!;
    final Paint paint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = height
      ..strokeCap = StrokeCap.round;
    final double width = rect.width - 2 * radius;
    final double arcHeight = radius;
    final Rect arcRect = Rect.fromLTWH(
      rect.left + radius,
      rect.bottom - arcHeight - height / 2,
      width,
      arcHeight * 2,
    );
    final Path path = Path();
    path.arcTo(arcRect, 0, pi, false);
    canvas.drawPath(path, paint);
  }
}
